package com.ruoyi.learn.java.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class ThreadInterrupt {
    public static void main(String[] args) throws InterruptedException {

        // 创建并启动一个执行阻塞操作的线程
        Thread worker = new Thread(() -> {
            BlockingQueue<String> queue = new LinkedBlockingQueue<>(1);
            try {
                // 阻塞等待入队（队列满时会阻塞）
                log.info("1");
                queue.put("data");
                log.info("2");
                queue.put("data");
                log.info("3");
            } catch (InterruptedException e) {
                System.out.println("线程被中断！");
                System.out.println("中断状态未恢复：" + Thread.currentThread().isInterrupted());

                // 处理中断...
                log.info("4");
                Thread.currentThread().interrupt();
                // 后续代码可通过 Thread.interrupted() 检测到中断
                System.out.println("中断状态已恢复：" + Thread.currentThread().isInterrupted());
            }
        });
        worker.start();

// 主线程在一段时间后中断 worker 线程
        log.info("主线程准备休眠");
        Thread.sleep(3000);
        log.info("主线程准备中断");
        worker.interrupt(); // 触发中断
        Thread.sleep(3000);
        log.info("中断状态未恢复：" + Thread.currentThread().isInterrupted());
        // 处理中断...
        log.info("4");
        Thread.currentThread().interrupt();
        // 后续代码可通过 Thread.interrupted() 检测到中断
        log.info("中断状态已恢复：" + Thread.currentThread().isInterrupted());

    }
}
